#!/usr/bin/env python
# -*- coding: utf-8 -*-
from cryptography.fernet import Fernet
import json
import os

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_CONF = BASE_DIR + "\\conf"
VAULT_FILE = os.path.join(BASE_CONF, 'spider.json')
ENCRYPT_FILE = VAULT_FILE
KEY_FILE = os.path.join(BASE_CONF, 'key.key')


# 生成密钥
def generate_key():
    key = Fernet.generate_key()
    with open(KEY_FILE, 'wb') as f:
        f.write(key)
    return key


# 加载密钥
def load_key():
    if os.path.exists(KEY_FILE):
        with open(KEY_FILE, 'rb') as f:
            return f.read()
    return None


# 加密函数
def encrypt_json(data, key):
    f = Fernet(key)
    json_data = json.dumps(data).encode()
    encrypted_data = f.encrypt(json_data)
    return encrypted_data


# 解密函数
def decrypt_json(encrypted_data, key):
    f = Fernet(key)
    decrypted_data = f.decrypt(encrypted_data)
    json_str = decrypted_data.decode('utf-8')
    return json.loads(json_str)


# 读取二进制文件
def read_byte_file(file_path):
    with open(file_path, 'r') as file:
        return file.read()


# 读取 JSON 数据
def read_json(file_path):
    with open(file_path, 'r') as file:
        return json.load(file)


# 写入二进制文件
def write_byte_file(file_path, data):
    with open(file_path, 'wb') as file:
        file.write(data)


# 写入 JSON 数据
def write_json(file_path, data):
    with open(file_path, 'w') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)


# 判断是否加密
def is_encrypted(encrypted):
    try:
        json.loads(encrypted)
        return False
    except Exception:
        return True


def read_encrypt_json(file_path, key):
    encrypted_data = read_byte_file(file_path)
    if is_encrypted(encrypted_data):
        print("加密文件，开始解密...")
        decrypted_data = decrypt_json(encrypted_data, key)
        return decrypted_data
    else:
        print("未加密文件，直接读取...")
        return json.loads(encrypted_data)


def write_encrypt_json(file_path, data, key):
    old_data = read_encrypt_json(file_path, key)
    if data is None:
        data = old_data
    # 遍历 data 中的键值对，更新 old_data
    for k, value in data.items():
        old_data[k] = value
    write_json(file_path, old_data)
    # 进行加密后再次写入
    encrypted_data = encrypt_json(old_data, key)
    write_byte_file(file_path, encrypted_data)


def write_public_json(file_path, data, key):
    old_data = read_encrypt_json(file_path, key)
    if data is None:
        data = old_data
    # 遍历 data 中的键值对，更新 old_data
    for k, value in data.items():
        old_data[k] = value
    write_json(file_path, old_data)


key = load_key()
if not key:
    key = generate_key()

glob_config = read_encrypt_json(ENCRYPT_FILE, key)
headers = glob_config.get('headers', {})
header_url = glob_config.get('header_url', '')
page = glob_config.get('page', 1)
spider_type = glob_config.get('spider_type', 'xpath')
proxy_pools = glob_config.get('proxy_pools', {})
product_keywords = glob_config.get('product_keywords', '')
log_path = glob_config.get("log_path")
log_name = glob_config.get("log_name")
log_level = glob_config.get("log_level")


def reload_config():
    """重新加载配置文件"""
    global glob_config, headers, header_url, page, spider_type, proxy_pools, product_keywords, log_path, log_name, log_level
    glob_config = read_encrypt_json(ENCRYPT_FILE, key)
    headers = glob_config.get('headers', {})
    header_url = glob_config.get('header_url', '')
    page = glob_config.get('page', 1)
    spider_type = glob_config.get('spider_type', 'xpath')
    proxy_pools = glob_config.get('proxy_pools', {})
    product_keywords = glob_config.get('product_keywords', '')
    log_path = glob_config.get("log_path")
    log_name = glob_config.get("log_name")
    log_level = glob_config.get("log_level")
# if __name__ == '__main__':
#     data = {
#         "page": 1,
#         "product_keywords": "饼干"
#     }
#     write_public_json(ENCRYPT_FILE, data, key)
#     # 读取未加密的 JSON 数据
#     print(read_json(VAULT_FILE))
#
#     # 写入文件后自动加密
#     write_encrypt_json(ENCRYPT_FILE, data, key)
#
#     # 读取加密的 JSON 数据
#     print(read_encrypt_json(ENCRYPT_FILE, key))
#
#     # 读取
#     __write_json(ENCRYPT_FILE, data, key)
